"""
数据模型基类
"""
from datetime import datetime
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declared_attr

from app.db.database import Base


class TimeStampMixin:
    """时间戳Mixin，添加创建和更新时间"""
    
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, comment="创建时间")
    updated_at = Column(
        DateTime,
        default=datetime.utcnow,
        onupdate=datetime.utcnow,
        nullable=False,
        comment="更新时间"
    )


class BaseModel(Base, TimeStampMixin):
    """
    所有模型的基类
    提供id、created_at、updated_at字段
    """
    __abstract__ = True
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True, comment="主键ID")
    
    @declared_attr
    def __tablename__(cls):
        """自动生成表名（类名的小写形式）"""
        return cls.__name__.lower()
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            column.name: getattr(self, column.name)
            for column in self.__table__.columns
        }
    
    def __repr__(self):
        """字符串表示"""
        return f"<{self.__class__.__name__}(id={self.id})>"

